const path = require('path')
// 导入terser-webpack-plugin-->减少js体积(其中删除js的console.log和注释)
const TerserWebpackPlugin = require('terser-webpack-plugin')
// 分析
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
// 实例化BundleAnalyzerPplugin对象
// const analyzerPlugin = new BundleAnalyzerPlugin()
const resolvePath = (dir) => path.join(__dirname, dir)
const isPro = ['production', 'prod'].includes(process.env.VUE_APP_MODE)
// 实例化TerserWebpackPlugin对象
const terserPlugin = new TerserWebpackPlugin({
  parallel: 4,
  extractComments: true,
  terserOptions: {
    compress: {
      warnings: false,
      drop_console: true,
      drop_debugger: true,
      pure_funcs: ['console.log'] // 移除console
    }
  }
})

module.exports = {
  publicPath: process.env.BASE_URL,
  outputDir: 'dist-' + process.env.outputDir,
  assetsDir: 'static',
  productionSourceMap: false, // 是否开启map映射源文件
  chainWebpack: (config) => {
    // 移除preload插件
    config.plugins.delete('preload')
    // 移除 prefetch 插件
    config.plugins.delete('prefetch')
    config.resolve.alias.set('@', resolvePath('src'))
    config.optimization.splitChunks({
      chunks: 'all',
      cacheGroups: {
        elementUI: {
          name: 'chunk-elementUI', // 将element-ui单独打包成一个文件
          priority: 20,
          test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
        },
        commons: {
          name: 'chunk-commons',
          test: resolvePath('src/components'),
          minChunks: 3,
          priority: 5,
          reuseExistingChunk: true
        }
      }
    })
    // if (isPro) {
    //   config.plugin('webpack-report').use(BundleAnalyzerPlugin, [
    //     {
    //       analyzerMode: 'static'
    //     }
    //   ])
    // }
  },
  configureWebpack: (config) => {
    if (isPro) {
      config.plugins.push(terserPlugin)
    }
  },
  devServer: {
    port: 40605,
    open: true,
    proxy: {
      '/api': {
        target: process.env.VUE_APP_URL,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}
